import 'package:flutter/material.dart';
import 'organization_model.dart';

class OrganizationForm extends StatefulWidget {
  final OrganizationModel? organization;
  final Function(Map<String, dynamic>) onSubmit;

  const OrganizationForm({
    Key? key,
    this.organization,
    required this.onSubmit,
  }) : super(key: key);

  @override
  _OrganizationFormState createState() => _OrganizationFormState();
}

class _OrganizationFormState extends State<OrganizationForm> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _nameController;
  late TextEditingController _levelController;
  late TextEditingController _contactPersonController;
  late TextEditingController _contactInfoController;
  late TextEditingController _remarkController;
  late TextEditingController _parentIdController;
  late TextEditingController _introductionController;
  late TextEditingController _paramsController;
  late TextEditingController _regionController;
  late TextEditingController _operatorIdController;
  late TextEditingController _salesIdController;
  late TextEditingController _licenseInfoController;
  late TextEditingController _contractExpireAtController;
  DateTime? _selectedContractExpireAt;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.organization?.name ?? '');
    _levelController = TextEditingController(text: widget.organization?.level.toString() ?? '1');
    _contactPersonController = TextEditingController(text: widget.organization?.contactPerson ?? '');
    _contactInfoController = TextEditingController(text: widget.organization?.contactInfo ?? '');
    _remarkController = TextEditingController(text: widget.organization?.remark ?? '');
    _parentIdController = TextEditingController(text: widget.organization?.parentId.toString() ?? '0');
    _introductionController = TextEditingController(text: widget.organization?.introduction ?? '');
    _paramsController = TextEditingController(text: widget.organization?.params ?? '');
    _regionController = TextEditingController(text: widget.organization?.region ?? '');
    _operatorIdController = TextEditingController(text: widget.organization?.operatorId.toString() ?? '0');
    _salesIdController = TextEditingController(text: widget.organization?.salesId.toString() ?? '0');
    _licenseInfoController = TextEditingController(text: widget.organization?.licenseInfo ?? '');
    
    if (widget.organization?.contractExpireAt != null) {
      _selectedContractExpireAt = widget.organization?.contractExpireAt;
      _contractExpireAtController = TextEditingController(
        text: _formatDate(widget.organization?.contractExpireAt)
      );
    } else {
      _contractExpireAtController = TextEditingController();
    }
  }

  String _formatDate(DateTime? date) {
    if (date == null) return '';
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedContractExpireAt ?? DateTime.now(),
      firstDate: DateTime.now(),
      lastDate: DateTime(2100),
    );
    if (picked != null && picked != _selectedContractExpireAt) {
      setState(() {
        _selectedContractExpireAt = picked;
        _contractExpireAtController.text = _formatDate(picked);
      });
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _levelController.dispose();
    _contactPersonController.dispose();
    _contactInfoController.dispose();
    _remarkController.dispose();
    _parentIdController.dispose();
    _introductionController.dispose();
    _paramsController.dispose();
    _regionController.dispose();
    _operatorIdController.dispose();
    _salesIdController.dispose();
    _licenseInfoController.dispose();
    _contractExpireAtController.dispose();
    super.dispose();
  }

  Future<void> _submitForm() async {
    if (!_formKey.currentState!.validate()) return;

    final data = {
      'name': _nameController.text,
      'level': int.parse(_levelController.text),
      'contact_person': _contactPersonController.text,
      'contact_info': _contactInfoController.text,
      'remark': _remarkController.text,
      'parent_id': int.parse(_parentIdController.text),
      'introduction': _introductionController.text,
      'params': _paramsController.text,
      'region': _regionController.text,
      'operator_id': int.parse(_operatorIdController.text),
      'sales_id': int.parse(_salesIdController.text),
      'license_info': _licenseInfoController.text,
      'contract_expire_at': _selectedContractExpireAt?.toIso8601String(),
    };

    try {
      widget.onSubmit(data);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('提交表单时发生错误：${e.toString()}'))
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          TextFormField(
            controller: _nameController,
            decoration: const InputDecoration(labelText: '机构名称'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入机构名称';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _levelController,
            decoration: const InputDecoration(labelText: '机构级别'),
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入机构级别';
              }
              if (int.tryParse(value) == null) {
                return '请输入有效的数字';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _contactPersonController,
            decoration: const InputDecoration(labelText: '联系人'),
          ),
          TextFormField(
            controller: _contactInfoController,
            decoration: const InputDecoration(labelText: '联系方式'),
          ),
          TextFormField(
            controller: _remarkController,
            decoration: const InputDecoration(labelText: '备注'),
            maxLines: 2,
          ),
          TextFormField(
            controller: _parentIdController,
            decoration: const InputDecoration(labelText: '父机构ID'),
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入父机构ID';
              }
              if (int.tryParse(value) == null) {
                return '请输入有效的数字';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _introductionController,
            decoration: const InputDecoration(labelText: '介绍'),
            maxLines: 3,
          ),
          TextFormField(
            controller: _paramsController,
            decoration: const InputDecoration(labelText: '参数'),
            maxLines: 2,
          ),
          TextFormField(
            controller: _regionController,
            decoration: const InputDecoration(labelText: '地区'),
          ),
          TextFormField(
            controller: _operatorIdController,
            decoration: const InputDecoration(labelText: '运营人员ID'),
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入运营人员ID';
              }
              if (int.tryParse(value) == null) {
                return '请输入有效的数字';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _salesIdController,
            decoration: const InputDecoration(labelText: '销售人员ID'),
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入销售人员ID';
              }
              if (int.tryParse(value) == null) {
                return '请输入有效的数字';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _licenseInfoController,
            decoration: const InputDecoration(labelText: '授权产品信息'),
            maxLines: 3,
          ),
          Row(
            children: [
              Expanded(
                child: TextFormField(
                  controller: _contractExpireAtController,
                  decoration: const InputDecoration(labelText: '合同到期时间'),
                  readOnly: true,
                  onTap: () => _selectDate(context),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.calendar_today),
                onPressed: () => _selectDate(context),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('取消'),
              ),
              const SizedBox(width: 8),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text(widget.organization == null ? '创建' : '更新'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}